package com.htgd.gardenexpo.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.GeConFoodRuleMapper;
import com.htgd.gardenexpo.dao.GeConFoodShopMapper;
import com.htgd.gardenexpo.entity.CommonResult;
import com.htgd.gardenexpo.entity.GeConFood;
import com.htgd.gardenexpo.dao.GeConFoodDao;
import com.htgd.gardenexpo.entity.GeConFoodRule;
import com.htgd.gardenexpo.entity.GeConFoodShop;
import com.htgd.gardenexpo.page.FoodQuery;
import com.htgd.gardenexpo.page.FoodRankQuery;
import com.htgd.gardenexpo.page.PageBase;
import com.htgd.gardenexpo.service.GeBaseDictService;
import com.htgd.gardenexpo.service.GeBaseUserService;
import com.htgd.gardenexpo.service.GeConFoodService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.htgd.gardenexpo.service.WxUserCollectService;
import com.htgd.gardenexpo.vo.GeConFoodRankingVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.htgd.gardenexpo.utils.CalculationUtils.calculateDistance;

/**
 * <p>
 * 美食表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-04-08
 */
@Service
public class GeConFoodServiceImpl extends ServiceImpl<GeConFoodDao, GeConFood> implements GeConFoodService {

    @Autowired
    private GeConFoodDao geConFoodDao;

    @Autowired
    private WxUserCollectService wxUserCollectService;

    @Autowired
    private GeConFoodRuleMapper geConFoodRuleMapper;

    @Autowired
    private GeBaseDictService geBaseDictService;

    @Autowired
    private GeBaseUserService geBaseUserService;

    @Autowired
    private GeConFoodShopMapper geConFoodShopMapper;

    @Override
    public PageInfo<GeConFood> querylist(FoodQuery foodQuery, String openId) {
        PageHelper.startPage(foodQuery.getPageNum(), foodQuery.getPageSize());
        List<GeConFood> list = geConFoodDao.querylist(foodQuery);
        for (GeConFood geConFood : list) {
            //收藏
            geConFood.setCollect(false);
            if(openId!=null){
                Boolean collect = wxUserCollectService.isLike(openId, String.valueOf(geConFood.getId()),"food");
                geConFood.setCollect(collect);
            }
            //点赞数
            Long collectAmount = wxUserCollectService.getCollectAmount(String.valueOf(geConFood.getId()), "food");
            geConFood.setCollectAmount(collectAmount);

            //标签
            if(geConFood.getType()!=null){
                String typeText = "";
                String[] split = geConFood.getType().split(",");
                for (String s : split) {
                    String food_type = geBaseDictService.getTextByCodeAndValue("food_type", s);
                    typeText = typeText + food_type + ",";
                }
                geConFood.setTypeText(typeText.substring(0,typeText.length()-1));
            }
        }
        return new PageInfo<>(list);
    }

    @Override
    public GeConFood queryById(Integer id) {
        return geConFoodDao.queryById(id);
    }

    @Override
    public void addHit(String id) {
        lambdaUpdate().setSql("hit = hit +1").eq(GeConFood::getId,id).update();
    }

    @Override
    public PageInfo<GeConFoodRankingVO> getRanking(FoodRankQuery foodRankQuery, String openId) {
        PageInfo<GeConFoodRankingVO> result = new PageInfo<>();
        //规则
        GeConFoodRule geConFoodRule = geConFoodRuleMapper.selectById("1");
        //数据
        List<GeConFoodRankingVO> list= geConFoodDao.getRanking();
        for (GeConFoodRankingVO geConFoodRankingVO : list) {
            //收藏量
            long collect = wxUserCollectService.getFoodCollectAmount(geConFoodRankingVO.getId());
            geConFoodRankingVO.setCollect(Math.toIntExact(collect));
            //热度
            int heat = Math.toIntExact(collect) * geConFoodRule.getCollect() + geConFoodRankingVO.getHit() * geConFoodRule.getHit();
            geConFoodRankingVO.setHeat(heat);

            //经纬度
            if (foodRankQuery.getLng() != null && !foodRankQuery.getLng().isEmpty()
                    && foodRankQuery.getLat() != null && !foodRankQuery.getLat().isEmpty()
                    && geConFoodRankingVO.getLng() != null && !geConFoodRankingVO.getLng().isEmpty()
                    && geConFoodRankingVO.getLat() != null && !geConFoodRankingVO.getLat().isEmpty()) {
                double distance = calculateDistance(foodRankQuery.getLat(), foodRankQuery.getLng(), geConFoodRankingVO.getLat(), geConFoodRankingVO.getLng());
                geConFoodRankingVO.setDistance(String.format("%.2f km",distance));
            }
        }

        // 获取前20条数据
        int toIndex = Math.min(20, list.size()); // 限制返回的最大条数为20
        // 对列表进行排序
        list.sort(Comparator.comparing(GeConFoodRankingVO::getHeat).reversed());
        // 判断是否超出列表范围
        if (toIndex == 0) {
            result.setList(new ArrayList<>());
        } else {
            result.setList(list.subList(0, toIndex)); // 只返回前20条
        }
        result.setTotal(list.size()); // 总数据量保持不变

        return result;
    }

    @Override
    public GeConFood details(Integer id,String openId) {
        GeConFood geConFood = geConFoodDao.selectById(id);
        //收藏
        geConFood.setCollect(false);
        if(openId!=null){
            Boolean collect = wxUserCollectService.isLike(openId, String.valueOf(id),"food");
            geConFood.setCollect(collect);
        }
        //点赞数量
        Long collectAmount = wxUserCollectService.getCollectAmount(String.valueOf(id), "food");
        geConFood.setCollectAmount(collectAmount);

        //标签
        if(geConFood.getType()!=null){
            String typeText = "";
            String[] split = geConFood.getType().split(",");
            for (String s : split) {
                String food_type = geBaseDictService.getTextByCodeAndValue("food_type", s);
                typeText = typeText + food_type + ",";
            }
            geConFood.setTypeText(typeText.substring(0,typeText.length()-1));
        }
        return geConFood;
    }

    @Override
    public CommonResult add(GeConFood geConFood) {
        geConFood.setStatus("4");
        geConFood.setDeleteFlag("0");
        geConFoodDao.insert(geConFood);
        return CommonResult.success("添加成功");
    }

    @Override
    public CommonResult edit(GeConFood geConFood) {
        if(geConFood.getEditorId() != null){
            geConFood.setEditorName(geBaseUserService.queryById(geConFood.getEditorId()).getUsername());
        }
        geConFoodDao.updateById(geConFood);
        return CommonResult.success("编辑成功");
    }

    @Override
    public CommonResult delete(int id) {
        lambdaUpdate().eq(GeConFood::getId,id)
                .set(GeConFood::getDeleteFlag,"1")
                .update();
        return CommonResult.success("删除成功");
    }

    @Override
    public CommonResult review(GeConFood geConFood) {
        if (geConFood.getPublisherId()!=null){
            geConFood.setPublisherName(geBaseUserService.queryById(geConFood.getPublisherId()).getUsername());
            geConFood.setReleasetime(new Date());
        }
        if (geConFood.getAuthUserId()!=null){
            geConFood.setAuthUser(geBaseUserService.queryById(geConFood.getAuthUserId()).getUsername());
            geConFood.setAuthtime(new Date());
        }
        geConFoodDao.updateById(geConFood);
        return CommonResult.success("审核成功");
    }
}
